/*
 * @lc app=leetcode.cn id=1143 lang=golang
 *
 * [1143] 最长公共子序列
 */

// 2. 动态规划
// @lc code=start
func longestCommonSubsequence(text1, text2 string) int {
	m, n := len(text1), len(text2)
	dp := make([][]int, m+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
	}

	for i := 1; i <= m; i++ {
		for j := 1; j <= n; j++ {
			if text1[i-1] == text2[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = max(dp[i-1][j], dp[i][j-1])
			}
		}
	}
	return dp[m][n]
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

// @lc code=end

// 1. 答案错误
// @lc code=start
func longestCommonSubsequence(text1 string, text2 string) (ans int) {
	queue := []string{text2}
	history := make(map[string]int)
	for len(queue) > 0 {
		temp := queue[0]
		queue = queue[1:]
		j := 0
		for i := 0; i < len(temp); i++ {
			for ; j < len(text1) && text1[j] != temp[i]; j++ {
			}
			j++
			if j >= len(text1) {
				if i != 0 && text1[len(text1)-1] == temp[i] {
					ans = max(ans, i+1)
				}
				if i != 0 && text1[len(text1)-1] != temp[i] {
					ans = max(ans, i)
				}
				break
			}
		}
		for i := 0; i < len(temp); i++ {
			if _, ok := history[temp[0:i]+temp[i+1:]]; !ok {
				queue = append(queue, temp[0:i]+temp[i+1:])
				history[temp[0:i]+temp[i+1:]] = 1
			}
		}
	}
	return
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

// @lc code=end

